package edu.friday.repository;

import edu.friday.model.SysMenu;
import edu.friday.repository.custom.SysMenuCustomRepository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.Set;

@Repository
public interface ISysMenuRepository extends JpaRepository<SysMenu, Long>, SysMenuCustomRepository {

    final String SELECT_DISTINCT = " select distinct m.menu_id, m.parent_id, " +
            "m.menu_name, m.path, m.component, m.visible, ifnull(m.perms,'') as perms, " +
            "m.is_frame, m.menu_type, m.icon, m.order_num, m.create_by, m.create_time, " +
            "m.update_by, m.update_time, m.remark from sys_menu m ";
    final String JOIN_ROLE_MENU = "LEFT JOIN sys_role_menu rm ON rm.menu_id=m.menu_id ";
    final String JOIN_USER_ROLE = "LEFT JOIN sys_user_role ur ON ur.role_id=rm.role_id";
    final String JOIN_ROLE = " left join sys_role ro on ur.role_id = ro.role_id ";
    final String JOIN_USER = " left join sys_user u on ur.user_id = u.user_id ";
    final String ORDER_BY = " order by m.parent_id, m.order_num ";

    @Query(value = "SELECT DISTINCT m.perms FROM sys_menu m " +
            JOIN_ROLE_MENU + JOIN_USER_ROLE +
            " WHERE ur.user_id = :userId", nativeQuery = true)
    Set<String> selectPermsByUserId(@Param("userId") Long userId);

    @Query(value = "select count(*) from sys_role_menu where menu_id = :menuId", nativeQuery = true)
    Long checkMenuExistRole(@Param("menuId") Long menuId);

    /**
     * 根据userId查找菜单类型是'M', 'C'并且角色状态正常,菜单可视
     * @param userId
     * @return
     */
    @Query(value = SELECT_DISTINCT + JOIN_ROLE_MENU + JOIN_USER_ROLE + JOIN_ROLE+ JOIN_USER +
            " where u.user_id = :userId and m.menu_type in ('M', 'C') and m.visible = 0  AND ro.status = 0 " +
            ORDER_BY, nativeQuery = true)
    List<SysMenu> selectMenuTreeByUserId(@Param("userId") Long userId);
}
